package com.sun.aop.aspect;

import com.sun.aop.annotation.RedisAnno;
import com.sun.aop.handler.AbstractHandler;
import com.sun.aop.handler.HandlerContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author 喻湘东
 * @Create 2019-09-22 16:44:57
 */
@Aspect
@Component
public class RedisAspect {

    @Autowired
    private HandlerContext handlerContext;

    @Pointcut("execution(* com.sun.aop.service.impl..*.*(..))")
    public void redisAspect(){}



    @Before("redisAspect()")
    public void doBefore(JoinPoint joinPoint){
        RedisAnno redisAnno = getAnnotation(joinPoint);
        if(redisAnno!=null){
            String methodName = redisAnno.methodName();
            String key = redisAnno.key(); // get hget hgetAll lrange
            AbstractHandler instanc = handlerContext.getInstanc(methodName);
            Object o = instanc.get(key);
            System.out.println("doBefore获取的值为："+o);
        }else{
            System.out.println("没有注解");
        }
    }
    @After("redisAspect()")
    public void doAfter(JoinPoint joinPoint){
        RedisAnno redisAnno = getAnnotation(joinPoint);
        if(redisAnno!=null){
            String methodName = redisAnno.methodName();
            String key = redisAnno.key(); // get hget hgetAll lrange

            AbstractHandler instanc = handlerContext.getInstanc(methodName);
            instanc.set(key,"喻湘东",10);
            Object o = instanc.get(key);
            System.out.println("doAfter获取的值为："+o);
        }else{
            System.out.println("没有注解");
        }
    }

    private RedisAnno getAnnotation(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method targetMethod = methodSignature.getMethod();
        return targetMethod.getAnnotation(RedisAnno.class);
    }


}
